package com.xiaoyu.base.net;

import in.srain.cube.util.internal.AppConsumer;

import com.xiaoyu.net.exception.AccessTokenExpiredException;
import com.xiaoyu.base.app.GlobalUI;

import in.srain.cube.request.CustomNetworkException;
import in.srain.cube.request.FailData;
import in.srain.cube.request.IRequest;
import in.srain.cube.util.CLog;
import in.srain.cube.util.Env;

public class NetworkErrorProcessor {

    private static final String TAG = "NetworkErrorProcessor";
    private static final int CUSTOM_CODE = 10000;
    public static final int ACCESS_TOKEN_EXPIRED = 1000;
    public static final int NEED_LOGIN = 1001;

    private static NetworkErrorProcessor sInstance;
    private static AppConsumer<CustomNetworkException> sNetworkExceptionConsumer;

    public static synchronized NetworkErrorProcessor getInstance() {
        if (sInstance == null) {
            sInstance = new NetworkErrorProcessor();
        }
        return sInstance;
    }

    public NetworkErrorProcessor() {
    }

    public static void setCustomNetworkExceptionConsumer(AppConsumer<CustomNetworkException> consumer) {
        sNetworkExceptionConsumer = consumer;
    }

    public <T> T processEEE(IRequest request, int errorCode, String message) throws AccessTokenExpiredException {
        if (errorCode == ACCESS_TOKEN_EXPIRED) {
            throw new AccessTokenExpiredException();
        }
        request.setFailData(FailData.customError(request, errorCode, message));
        return null;
    }

    public void onRequestFail(IRequest request, Object requestTag, FailData failData) {
        final Exception exception = failData.getException();
        CLog.e(TAG, "onRequestFail: %s %s", exception.getMessage(), request.getRequestData());
        if (Env.isDevOrInDevMode()) {
            GlobalUI.getInstance().showToast("message only for dev: " + failData.getException().getMessage());
        }
        if (!(exception instanceof CustomNetworkException)) {
            return;
        }
        final CustomNetworkException customNetworkException = (CustomNetworkException) exception;
        sNetworkExceptionConsumer.accept(customNetworkException);

        if (customNetworkException.code >= CUSTOM_CODE) {
            // dismiss global loading
            GlobalUI.getInstance().showToast(failData.getException().getMessage());
        }
    }
}
